// pages/supply/supply.js
var network = require("../../utils/request.js"); //网络请求
var calls = require("../../utils/city.js"); //城市信息
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:"",//有表示为编辑，无表示为新增
    inputValue: '',//点击结果项之后替换到文本框的值
    bindSource: [],//绑定到页面的数据，根据用户输入动态变化
    isShowHint: false,//是否显示联想内容
    icon_img: "../../resource/images/arrow_down.png",
    sizeArr: [],
    sizeIndex: 0, 
    unitArr:[],
    unitIndex:0,
    goodsName: "",
    goodsId: "",//规格id，必传参数
    amount: "",//数量
    price: "",//价格
    address:"",//库存地址
    yieldlyItem:[],//药材产地
    yieldly:'请选择',
    yieldlyRegion: "",//区域栏选中的值
    details:"",//描述
    playType:1,//支付类型

    province:"",//省
    city:"", //市
    area:"", //区
    userInfo: {},
    radioItems: [
      { value: '现金', id: 1, checked: 'true' },
      { value: '账期', id: 2 },
      { value: '其他', id: 0 },
    ],
    token:"",//获取缓存里面的token
    uploadImgs: [],//上传的图片
    serverImg:[],//上传到服务器的图片id集合
    showUpBtn: false,//是否上传了9张图片
    dataInfo:{},//点击编辑按钮进入，传过来的对象
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    if (options.id){
      //如果有传过来的值
      network.post('getProvision/' + options.id).then(resp => {
        console.log(resp.rows)
        this.setData({
          dataInfo: resp.rows, //数据源
          id: resp.rows.id, //数据id
          inputValue: resp.rows.name, //品种名称
          goodsId: resp.rows.goodsId, //规格id
          province: resp.rows.province, //省
          city: resp.rows.city, //市
          area: resp.rows.area, //区
          yieldly: resp.rows.province + resp.rows.city + resp.rows.area, //药材产地
          address: resp.rows.address, //地址
          details: resp.rows.details, //描述
          amount: resp.rows.amount, //数量
          price: resp.rows.price, //价格
          detailImages: resp.rows.detailImgs, //商品图片
          playType: resp.rows.playType, //交易类型
        })

        //获取付款方式的默认选中项
        for (let index in that.data.radioItems){
          if (that.data.playType === that.data.radioItems[index].id){
            this.setData({
                [`radioItems[${index}].checked`]:true
            })
          }else{
            this.setData({
              [`radioItems[${index}].checked`]: false
            })
          }
        }

        //获取图片
        let imgArr = []
        let imgArrId = []
        for (let item in resp.rows.detailImgs){
          imgArr.push(resp.rows.detailImgs[item].url)
          imgArrId.push(resp.rows.detailImgs[item].url.split("show/")[1].split("?")[0])
        }
        that.setData({
          uploadImgs: imgArr, //商品图片
          serverImg: imgArrId,//商品图id 截取
        })

        //获取规格下拉数据源
        network.post('getGoodsByName/' + that.data.inputValue).then(resp => {
          console.log(resp)
          if (resp.rows.length > 0) {
            resp.rows.unshift({
              "standard": " "
            })
            that.setData({
              sizeArr: resp.rows
            })
          } else {
            let arr = { "standard": " " }
            that.setData({
              sizeArr: arr
            })
          }

          //获取规格数组的下标
          for (let item in that.data.sizeArr) {
            if (that.data.dataInfo.standard === that.data.sizeArr[item].standard) {
              that.setData({
                sizeIndex: item
              })
            }
          }
        })
        //getGoodsByName接口end

      })
      //getProvision接口end


    }
    
  },

  //规格选择
  bindSize(e) {
    let id = this.data.sizeArr[e.detail.value].id
    this.setData({
      sizeIndex: e.detail.value,
      goodsId: id
    })
  },

  //药材产地
  bindYieldly(e){
    //为了让选择框有个默认值，    
    this.setData({
      clas: ''
    })

    this.setData({
      //省市区字符串传后台
      province: e.detail.value[0],
      city: e.detail.value[1],
      area: e.detail.value[2],
      //下拉框选中的值
      yieldly: e.detail.value.join(""),
      //给下面的库存地赋值
      address: e.detail.value.join("")
    })
  },

  //获取iniput框的值
  getGoodsName(e){
    var that = this
    var prefix = e.detail.value//用户实时输入值
    if (prefix != "") {
      //通过接口查询数据
      network.post('getTradeByName/' + prefix).then(resp => {
        console.log(resp.rows)
        if (resp.rows.length > 0) {
          that.setData({
            bindSource: resp.rows,
            isShowHint: true
          })
        } else {
          that.setData({
            bindSource: [],
            isShowHint: false
          })
        }
      })
    }

  },

  itemtap: function (e) {
    this.setData({
      inputValue: e.target.id,
      bindSource: [],
      isShowHint: false
  })
    //获取规格下拉数据源
    network.post('getGoodsByName/' + e.target.id).then(resp => {
      console.log(resp)
      if (resp.rows.length > 0) {
        resp.rows.unshift({
          "standard": " "
        })
        this.setData({
          sizeArr: resp.rows,
          sizeIndex: 1
        })
      } else {
        let arr = { "standard": " " }
        this.setData({
          sizeArr: arr
        })
      }
    })
  },

  //获取库存数量
  getAmount(e) {
    this.setData({
      amount: e.detail.value.replace(/\s+/g, '')
    })
  },

  //获取价格
  getPrice(e) {
    this.setData({
      price: e.detail.value.replace(/\s+/g, '')
    })
  },

  //库存地址
  getAddress(e) {
    this.setData({
      address: e.detail.value.replace(/\s+/g, '')
    })
  },

  //获取textArea框的值
  getDetails(e) {
    this.setData({
      details: e.detail.value.replace(/\s+/g, '')
    })
  },

  //获取付款方式
  radioChange(e){
    this.setData({
      playType: e.detail.value
    })
  },

  //上传图片
  uploadImg(){
    var that = this
    wx.chooseImage({
      count:1,//最大上传数
      sizeType: ['original', 'compressed'],//原图，压缩图
      sourceType: ['album', 'camera'],//从相册中选择，使用相机
      success: function(res) {
        var tempFilePaths = res.tempFilePaths;
        that.setData({
          uploadImgs: that.data.uploadImgs.concat(tempFilePaths[0])
        })

        //上传到服务器
        that.uploadimg(that, tempFilePaths[0])

        if (that.data.uploadImgs.length === 9) {
          //如果上传了9张，则隐藏上传按钮
          that.setData({
            showUpBtn: true
          })
        }
      },
    })
  },

  uploadimg(that, path) {
    wx.showToast({
      icon: 'loading',
      title: '正在上传',
    }),
    wx.uploadFile({
      url: network.APP_URL + 'upload/image',
      filePath: path,
      dataType: "json",
      name: 'file',
      header: {
        "Authentication": that.data.token
      },
      success: function (res) {
        let imgData = JSON.parse(res.data)
        that.setData({
          serverImg: that.data.serverImg.concat(imgData.rows)
        })
      }
    })
  },

  

  //预览图片
  previewImg: function (e) {
    var img = e.currentTarget.dataset.url;
    // 设置预览图片路径
    wx.previewImage({
      current: img,
      urls: [img]
    })
  },

  //删除上传的图
  delImg(e){
    var imgs = this.data.uploadImgs
    let server = this.data.serverImg
    var index = e.currentTarget.dataset.index
    imgs.splice(index, 1)
    server.splice(index, 1)
    this.setData({
      uploadImgs: imgs,
      serverImg: server,
      showUpBtn: false
    });
  },

  //发布
  btnNext(){
    //判断非空
    if (this.data.inputValue == "") {
      wx.showToast({
        title: '请输入药材名称',
      })
      return
    }
    if (this.data.goodsId == "") {
      wx.showToast({
        title: '请输入规格',
      })
      return
    }
    if (this.data.amount == "") {
      wx.showToast({
        title: '请输入数量',
      })
      return
    }
    if (this.data.price == "") {
      wx.showToast({
        title: '请输入价格',
      })
      return
    }
    if (this.data.details == "") {
      wx.showToast({
        title: '请输入描述',
      })
      return
    }

    //把参数拼接成对象
    let arrInfo = {
      "id": parseInt(this.data.id),
      "goodsId": parseInt(this.data.goodsId),
      "province": this.data.province,
      "city": this.data.city,
      "area": this.data.area,
      "address": this.data.address,
      "details": this.data.details,
      "amount": parseInt(this.data.amount),
      "price": parseInt(this.data.price),
      "detailImages": this.data.serverImg,
      "playType": parseInt(this.data.playType),
    }
    network.post("saveProvision", arrInfo).then(resp => {
      console.log(resp)
      wx.showToast({
        title: '发布成功',
      })
      setTimeout(function(){
        wx.navigateBack({})
      },1000)
    })
  },

  //继续发布
  btnNextAngin(){
    var that = this
    //判断非空
    if (this.data.inputValue == "") {
      wx.showToast({
        title: '请输入药材名称',
      })
      return
    }
    if (this.data.goodsId == "") {
      wx.showToast({
        title: '请选择规格',
      })
      return
    }
    if (this.data.amount == "") {
      wx.showToast({
        title: '请输入数量',
      })
      return
    }
    if (this.data.price == "") {
      wx.showToast({
        title: '请输入价格',
      })
      return
    }
    if (this.data.details == "") {
      wx.showToast({
        title: '请输入描述',
      })
      return
    }

    //把参数拼接成对象
    let arrInfo = {
      "id": parseInt(this.data.id),
      "goodsId": parseInt(this.data.goodsId),
      "province": this.data.province,
      "city": this.data.city,
      "area": this.data.area,
      "address": this.data.address,
      "details": this.data.details,
      "amount": parseInt(this.data.amount),
      "price": parseInt(this.data.price),
      "detailImages": this.data.serverImg,
      "playType": parseInt(this.data.playType),
    }
    network.post("saveProvision", arrInfo).then(resp => {
      console.log(resp)
      wx.showToast({
        title: '发布成功',
      })
      setTimeout(function () {
        // wx.redirectTo({
        //   url: 'supply',
        // })
        //清空页面上的一些数据
        that.setData({
          inputValue: "",
          sizeArr: [],
          sizeIndex: 0
        })
      }, 1000)
    })
  },

  //跳转到修改手机号
  toModifyPhone(){
    wx.navigateTo({
      url: '../modifyPhone/modifyPhone',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let wxToken = wx.getStorageSync("token")
    let userInfo = wx.getStorageSync("userInfo")
    this.setData({
      token: wxToken,
      userInfo: userInfo
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '跑合中药材供需云平台',
      imageUrl: '../../resource/images/share.jpg',
      path: 'pages/supplyList/supplyList',
      success: function (res) {
        wx.showToast({
          title: '分享成功',
        })
      },
      fail: function (res) {
        // 转发失败
        wx.showToast({
          title: '分享取消',
        })
      }
    }
  }
})